#include "tree.h"
#include <stdlib.h>
#include <stdio.h>

//tree_t* findnode(tree_t* root, datatype data);

tree_t* InitTree(datatype data)
{
	tree_t* root = (tree_t*)malloc(sizeof(tree_t));
	if (root == NULL)
		return NULL;
	root->data = data;
	root->left = NULL;
	root->right = NULL;
	return root;
}

int InsertTree(tree_t* root, datatype data)
{
	tree_t* new_node = InitTree(data);
	if (new_node == NULL)
		return MEMORYMALLOCFALSE;
	while (root != NULL) {
		if (data < root->data) {
			if (root->left == NULL)
				break;
			root = root->left;
		} else {
			if (root->right == NULL)
				break;
			root = root->right;
		}
	}
	if (data < root->data)
		root->left = new_node;
	else
		root->right = new_node;
}
/*
int DeleteRoot(tree_t** root, datatype data)
{
	if (root == NULL)
		return TREEISNULL;
	if (*root == NULL)
		return TREEISNULL;
	tree_t* temp = findnode(*root, data);
	if (temp == NULL)
		return 0;
	tree_t* free_node = temp;
	if (temp->left == NULL && temp->right == NULL)
		;
	else if (temp->left != NULL && temp->right == NULL)
		temp = temp->left;
	else if (temp->left == NULL && temp->right != NULL)
		temp = temp->right;
	else if (temp->left != NULL && temp->right != NULL) {
		temp->left->right = temp->right;
		temp = temp->left;
	}
	free(free_node);
	free_node = NULL;
	return 0;
}

tree_t* findnode(tree_t* root, datatype data)
{
	while (root != NULL || data != root->data) {
		if (data < root->data) {
			if (root->left == NULL)
				break;
			root = root->left;
		} else {
			if (root->right == NULL)
				break;
			root = root->right;
		}
	}
	if (data != root->data)
		return NULL;
	return root;
}
*/
void PrintTreePre(tree_t* root)
{
	if (root == NULL)
		return;
	putchar(root->data);
	PrintTreePre(root->left);
	PrintTreePre(root->right);
}

void PrintTreeMid(tree_t* root)
{
	if (root == NULL)
		return;
	PrintTreeMid(root->left);
	putchar(root->data);
	PrintTreeMid(root->right);
}

void PrintTreeErr(tree_t* root)
{
	if (root == NULL)
		return;
	PrintTreeErr(root->left);
	PrintTreeErr(root->right);
	putchar(root->data);
}

void DestroyTree(tree_t** root)
{
	if (*root == NULL)
		return;
	DestroyTree(&((*root)->left));
	DestroyTree(&((*root)->right));
	free(*root);
	*root = NULL;
}